package com.sgkusbcamdemo;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.gkusbsdk.SZUSBCommand;
import com.gkusbsdk.SZUSBFile;
import com.gkusbsdk.SZUSBSDK;
import com.qitianyong.selfclass.BUS_MESSAGE;
import com.qitianyong.selfclass.CONSTANT;
import com.qitianyong.selfclass.FindDeviceUtils;
import com.qitianyong.selfclass.GKDevice;
import com.qitianyong.selfclass.LogUtils;
import com.qitianyong.selfclass.Message2EventBus;
import com.tencent.bugly.crashreport.CrashReport;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private Button mControlSearchDevice;
    private TextView mRecordStatus;
    private TextView mSdStatus;
    /**
     * 获取预览视频数据
     */
    private Button mGetPreviewData;
    /**
     * 拍照
     */
    private Button mCapture;
    /**
     * 开关录像
     */
    private Button mToggleRecord;
    /**
     * 格式化
     */
    private Button mFormat;
    /**
     * 恢复出厂设置
     */
    private Button mRestoreFactory;
    /**
     * 加锁当前
     */
    private Button mLockCurrent;
    /**
     * 获取文件列表
     */
    private Button mGetFileList;
    /**
     * 设置设备
     */
    private Button mSetting;
    private boolean sdExsit;
    private int recordStatusBak;
    private int exit_filelist_times;
    private int getLockErrCount;
    private int getSdProgressSameCount;
    private int curSDFormatProgress;
    private View buttonContentLayout;

    boolean startLockVideo =false;
    private Button mCaptureGet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initView();
        if(GKDevice.__hDevice == 0){
            FindDeviceUtils.findDevice();
        }else {
            GKDevice.getInstance().openStream();
        }
        LogUtils.i("System","MainActivity");
        mControlSearchDevice.setEnabled(false);
        mControlSearchDevice.setText("等待设备中..");


        //设置demo打印log
        LogUtils.LogEnable = BuildConfig.DEBUG;
        //设置sdk打印log
//        SZUSBSDK.GKUSB_SetLogEnable(true);
//        CrashReport.testJavaCrash();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressed();
                return false;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initView() {
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);

        mRecordStatus = (TextView) findViewById(R.id.record_status);
        buttonContentLayout =  findViewById(R.id.button_content_layout);
        mSdStatus = (TextView) findViewById(R.id.sd_status);
        mControlSearchDevice = (Button) findViewById(R.id.control_search_device);

        mGetPreviewData = (Button) findViewById(R.id.get_preview_data);
        mGetPreviewData.setOnClickListener(this);
        mCapture = (Button) findViewById(R.id.capture);
        mCapture.setOnClickListener(this);
        mCaptureGet = (Button) findViewById(R.id.capture_get);
        mCaptureGet.setOnClickListener(this);
        mToggleRecord = (Button) findViewById(R.id.toggle_record);
        mToggleRecord.setOnClickListener(this);
        mFormat = (Button) findViewById(R.id.format);
        mFormat.setOnClickListener(this);
        mRestoreFactory = (Button) findViewById(R.id.restore_factory);
        mRestoreFactory.setOnClickListener(this);
        mLockCurrent = (Button) findViewById(R.id.lock_current);
        mLockCurrent.setOnClickListener(this);
        mGetFileList = (Button) findViewById(R.id.get_file_list);
        mGetFileList.setOnClickListener(this);
        mSetting = (Button) findViewById(R.id.setting);
        mSetting.setOnClickListener(this);
    }

    @Override
    public void onBackPressed() {
        //用于退出应用时，退出线程、以及关闭资源
        GKDevice.getInstance().Destroy();
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.capture || id == R.id.format || id == R.id.lock_current || id == R.id.get_file_list) {
            if(!sdExsit){
                toast("无sd卡");
                return;
            }

        }
        switch (id) {
            case R.id.get_preview_data:
               startActivity(new Intent(this,ShowPreviewDataActivity.class));
                break;
            case R.id.capture:
                SZUSBFile usbFile = new SZUSBFile();
                usbFile.__lock = SZUSBCommand.FILE_TYPE.PHOTO_FILE;
                usbFile.__command = SZUSBCommand.PHOTO_FILE_CONTROL.CONTROL_CAPTURE;
                int ret = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_FILE_CONTROL, usbFile);
                if (ret != -1) {
                    showDialog();
                }
                break;
            case R.id.capture_get:
                new CaptureAndGetDataDialog(MainActivity.this).show();
                break;
            case R.id.toggle_record:
                int i3 = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_SETRECORD_STATUS, null);
                if (i3 != -1) {
                    showDialog();
                }
                break;
            case R.id.format:
                int ret1 = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_SET_SDCARD_FORMAT, null);
                if (ret1 != -1) {
                    showDialog();
                    getSdProgressSameCount = 20;
                    curSDFormatProgress = 0;
                }
                break;
            case R.id.restore_factory:
                int i1 = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_DEFAULT_FACTORY, null);
                if (i1 != -1) {
                    showDialog();
                }
                break;
            case R.id.lock_current:
                SZUSBFile usbFile1 = new SZUSBFile();
                usbFile1.__lock = SZUSBCommand.FILE_TYPE.HURRY_FILE;
                usbFile1.__command = SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_CAPTURE2LOCK;

                int i2 = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_FILE_CONTROL, usbFile1);
                if (i2 != -1) {
                    showCancelButtonDialog("asd", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SZUSBFile usbFile1 = new SZUSBFile();
                            usbFile1.__lock = SZUSBCommand.FILE_TYPE.HURRY_FILE;
                            usbFile1.__command = SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_CANCEL_CAPTURE2LOCK;
                            int i2 = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_FILE_CONTROL, usbFile1);
                        }
                    });
                }
                break;
            case R.id.get_file_list:
                //退出GalleryActivity需要发送CMD_EXIT_FILELIST  见GalleryActivity.onBackPressed
                int i = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_ENTER_FILELIST, null);
                if (i != -1) {
                    showDialog();
                }
                break;
            case R.id.setting:
                startActivity(new Intent(this,SettingActivity.class));
                break;
        }
    }

    public void onEventMainThread(Message2EventBus message) {

        switch (message.__what) {
            case BUS_MESSAGE.BUS_OPENSTREAM_OK: {
                mControlSearchDevice.setText("开流成功");
                buttonContentLayout.setVisibility(View.VISIBLE);
                break;
            }
            case BUS_MESSAGE.BUS_OFFLINE: {
                // 掉线清理
                buttonContentLayout.setVisibility(View.INVISIBLE);
                mRecordStatus.setText("未录像");
                sdExsit = false;
                mSdStatus.setText("sd卡未插入");
                mControlSearchDevice.setText("搜索设备ing..");
                recordStatusBak = SZUSBCommand.STATUS_RECORD.RECORD_UNKNOWN;
                cancelDialog();

                break;
            }
            case BUS_MESSAGE.BUS_ENTER_FILELIST: {

                if (((int) message.object) != -1) { // 进入成功，打开图库
                    Intent inGallery = new Intent(this, GalleryActivity.class);
                    inGallery.putExtra("status", recordStatusBak);
                    startActivity(inGallery);
                }
                cancelDialog();

                break;
            }
            case BUS_MESSAGE.BUS_EXIT_FILELIST: {
                //执行 EXIT_FILELIST 失败 10 次后不再执行
                if (((int) message.object) == -1 && exit_filelist_times < 10) {
                    exit_filelist_times++;
                    GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_EXIT_FILELIST, null);
                } else {
                    exit_filelist_times = 0;
                }
                break;
            }
            case BUS_MESSAGE.BUS_SDCARD_EXSIT: {

                /*int status = (int) message.object;
                if (status == GKUSBCommand.RESULT_SDCARD_EXSIT.EXSIT) {
                    __icon_sdcard.setImageResource(R.drawable.icon_def_sd_card);
                    sdExsit = true;
                } else {
                    __icon_sdcard.setImageResource(R.drawable.icon_def_sd_card_out);
                    sdExsit = false;
                }*/
                break;
            }
            case BUS_MESSAGE.BUS_GET_SDCARD_FORMAT: {

                int status = (int) message.object;
                if (status == -1 || status == 255 || getSdProgressSameCount == 0) {
                    toast("格式化错误");
                    cancelDialog();
                } else if (status == 100) {
                    cancelDialog();
                    toast("格式化完成");
                } else {
                    if (curSDFormatProgress != status) {

                        curSDFormatProgress = status;
                        getSdProgressSameCount = 20;
                        LogUtils.i("format", "curSDFormatProgress reset:" + status);
                    } else {
                        getSdProgressSameCount--; // 20次格式化一直为同一个值
                        LogUtils.i("format", "curSDFormatProgress-1:" + getSdProgressSameCount);
                    }
                    GKDevice.getInstance().sendCommand(
                            CONSTANT.COMMAND.CMD_GET_SDCARD_FORMAT, null);
                    showDialog(status + "%");
                }
                break;
            }
            case BUS_MESSAGE.BUS_GETRECORD_STATUS: {

                int status = (int) message.object;

                if (status == SZUSBCommand.STATUS_RECORD.RECORDING || status == SZUSBCommand.STATUS_RECORD.NORECORD_EXSIT_SD) {
                    mSdStatus.setText("sd卡已插入");
                    sdExsit = true;
                } else {
                    mSdStatus.setText("sd卡未插入");
                    sdExsit = false;
                }

                if (status == SZUSBCommand.STATUS_RECORD.RECORDING) {

                    mRecordStatus.setText("录像中");
                    if (recordStatusBak != status &&
                            recordStatusBak != SZUSBCommand.STATUS_RECORD.RECORD_UNKNOWN) {
                        toast("录像开启");
                    }
                } else {
                    mRecordStatus.setText("未录像");
                    if (recordStatusBak != status &&
                            recordStatusBak != SZUSBCommand.STATUS_RECORD.RECORD_UNKNOWN &&
                            status == SZUSBCommand.STATUS_RECORD.NORECORD_EXSIT_SD) {
                        toast("未录像");
                    }
                }
                recordStatusBak = status;
                break;
            }
            case BUS_MESSAGE.BUS_SET_SDCARD_FORMAT: {
                int status = (int) message.object;
                if (status != -1) { // 格式化指令发送成功
                    // 开线程检测SD卡格式化进度
                    GKDevice.getInstance().sendCommand(
                            CONSTANT.COMMAND.CMD_GET_SDCARD_FORMAT, null);
                }
                break;
            }
            case BUS_MESSAGE.BUS_SETRECORD_STATUS: {
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_CONTROL_ERR: {
                SZUSBFile usbFile = (SZUSBFile) message.object;
                if (usbFile.__lock == SZUSBCommand.FILE_TYPE.PHOTO_FILE) {
                    switch (usbFile.__command) {
                        case SZUSBCommand.PHOTO_FILE_CONTROL.CONTROL_CAPTURE: {
                            toast("抓拍失败");
                            cancelDialog();
                            break;
                        }
                        default:
                            break;
                    }
                } else {
                    switch (usbFile.__command) {
                        case SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_CAPTURE2LOCK: {
                            toast("加锁失败");
                            cancelCancelButtonDialog();
                            break;
                        }
                        case SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_CANCEL_CAPTURE2LOCK: {
                            toast("取消加锁失败");
                            break;
                        }
                        default:
                            break;
                    }

                }
                break;
            }
            case BUS_MESSAGE.BUS_CONTROL_OK: {
                SZUSBFile usbFile = (SZUSBFile) message.object;
                if (usbFile.__lock == SZUSBCommand.FILE_TYPE.PHOTO_FILE) {
                    switch (usbFile.__command) {
                        case SZUSBCommand.PHOTO_FILE_CONTROL.CONTROL_CAPTURE: {
                            cancelDialog();
                            toast("抓拍成功 " +new String(usbFile.__name));
                            break;
                        }
                        default:
                            break;
                    }
                } else {
                    switch (usbFile.__command) {
                        case SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_CAPTURE2LOCK: {
                            getLockErrCount = 20;
                            startLockVideo = true;
                            GKDevice.getInstance().sendCommand(
                                    CONSTANT.COMMAND.CMD_GETLOCK_PROGRESS, null);
                            break;
                        }
                        case SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_CANCEL_CAPTURE2LOCK: {
                            toast("取消加锁成功");
                            startLockVideo = false;
                            GKDevice.getInstance().clearSpeciallyTypeCommand(CONSTANT.COMMAND.CMD_GETLOCK_PROGRESS);
                            break;
                        }
                        default:
                            break;
                    }
                }
                break;
            }
            case BUS_MESSAGE.BUS_DEFAULT_FACTORY: {
                int status = (int) message.object;
                if (status == -1) {
                    toast("恢复出场失败");
                } else {
                    toast("恢复出场成功");
                }
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_PRINT: {

                break;
            }
            case BUS_MESSAGE.BUS_RECORD_HURRY: {
                if(!startLockVideo){
                    cancelCancelButtonDialog();
                    break;
                }
                int status = (int) message.object;
                if (status == 1 || getLockErrCount == 0) {

                    if (getLockErrCount == 0) {
                        toast("加锁失败");
                        LogUtils.i("lock", "----------lock record err--------");
                    } else {
                        LogUtils.i("lock", "----------lock record ok--------");
                        toast("加锁成功");
                    }
                    startLockVideo = false;
                    cancelCancelButtonDialog();
                } else {
                    if (status == -1) {
                        getLockErrCount--;
                        LogUtils.i("lock", "----------(getLockErrCount--)--------");
                    } else
                        LogUtils.i("lock", "----------status:" + status);
                    int i = GKDevice.getInstance().sendCommand(
                            CONSTANT.COMMAND.CMD_GETLOCK_PROGRESS, null);
                    if(i == -1){
                        startLockVideo = false;
                        cancelCancelButtonDialog();
                    }
                }

                break;
            }
            case BUS_MESSAGE.BUS_OPEN_RECORD: {
                LogUtils.i("GKDevice", "manal open record");
                GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_SETRECORD_STATUS, null);
                break;
            }
            default:
                break;
        }
    }

}
